package com.graduate.daydayup.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.AlarmClock
import android.text.TextUtils
import android.util.Log
import androidx.annotation.RequiresApi
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.graduate.daydayup.App
import com.graduate.daydayup.R
import com.graduate.daydayup.base.BaseActivity
import com.graduate.daydayup.room.MyRoomDataBase
import com.graduate.daydayup.room.Schedule
import com.graduate.daydayup.view.MyPickerView
import kotlinx.android.synthetic.main.activity_lessonadd.*
import java.util.*
import kotlin.collections.ArrayList
import kotlin.random.Random

class LessonAddActivity: BaseActivity() {
    override fun setTitle()="添加课程"
    val default="8:20,\n9:15,\n10:15,\n11:10,\n13:00,\n13:55,\n14:50,\n16:45,\n18:30,\n19:25,\n20:20"

     var start=1
     var step=1
     var day=1
    override fun getLayout()= R.layout.activity_lessonadd

    override fun setTextRight()="确定"
    lateinit var roomSchedule:Schedule
    lateinit var weeklist:String
    override fun setImgRightListener() {
        if (TextUtils.isEmpty(et_lesson_name.text.toString())){
            ToastUtils.showShort("课程名为空")
            return
        }
        if (TextUtils.isEmpty(et_lesson_teacher.text.toString())){
            ToastUtils.showShort("老师为空")
            return
        }
        if (TextUtils.isEmpty(tv_weeks.text.toString())){
            ToastUtils.showShort("上课地点为空")
            return
        }
        if (TextUtils.isEmpty(et_lesson_location.text.toString())){
            ToastUtils.showShort("上课地点为空")
            return
        }
        if (TextUtils.isEmpty(et_lesson_location.text.toString())){
            ToastUtils.showShort("上课地点为空")
            return
        }
        val allByDayAndName = MyRoomDataBase.getInstance(App.instance!!).scheduleDao()
            .getAllByDayAndName(day, et_lesson_name.text.toString())
        if (allByDayAndName!=null&&!allByDayAndName.name.isEmpty()){
            ToastUtils.showShort("不允许一天内存在重复课程！")
            return
        }
        val random = Random(10)
        roomSchedule=com.graduate.daydayup.room.Schedule(
            0, et_lesson_name.text.toString(), et_lesson_location.text.toString(),
            et_lesson_teacher.text.toString(), weeklist, start, step-start+1, day,
            random.nextInt()
        )
        MyRoomDataBase.getInstance(App.instance!!).scheduleDao().addSchedule(roomSchedule)
        if (SPUtils.getInstance().getString("lessontime")!=null&&!SPUtils.getInstance().getString("lessontime").isEmpty()){
            val replace = SPUtils.getInstance().getString("lessontime").replace("\n", "")
            val split = replace.split(",")
            val split1 = split[start - 1].split(":")
            Log.d("设置闹钟", split1[0] + split1[1])
            setSystemAlarmClock(
                this,
                "在${roomSchedule.room}上${roomSchedule.teacher}的${roomSchedule.name}",
                day,
                split1[0].toInt(),
                split1[1].toInt()
            )
        }else{
            val replace = default.replace("\n", "")
            val split = replace.split(",")
            val split1 = split[start - 1].split(":")
            Log.d("设置闹钟", split1[0] + split1[1])
            setSystemAlarmClock(
                this,
                "在${roomSchedule.room}上${roomSchedule.teacher}的${roomSchedule.name}",
                day,
                split1[0].toInt(),
                split1[1].toInt()
            )
        }
        ToastUtils.showShort("添加成功")
        finish()
        MyRoomDataBase.getInstance(App.instance!!).scheduleDao().getAll()
    }

    override fun isAddToolbar()=true

    override fun initViewIds() {

    }

    @RequiresApi(Build.VERSION_CODES.KITKAT)
    @SuppressLint("SetTextI18n")
    override fun initView() {
         start = intent.getIntExtra("start", 1)
         step = intent.getIntExtra("start", 1)
         day = intent.getIntExtra("day", 1)
            var dayString=""
            when(day){
                1->dayString="一"
                2->dayString="二"
                3->dayString="三"
                4->dayString="四"
                5->dayString="五"
                6->dayString="六"
                7->dayString="日"
            }
            tv_weekdays.setText("周${dayString}第${start}节第${step}节")
        if (start!=0){
            if (SPUtils.getInstance().getString("lessontime")!=null&& SPUtils.getInstance().getString(
                            "lessontime"
                    ).isNotEmpty()){
                val replace = SPUtils.getInstance().getString("lessontime").replace("\n", "")
                val split = replace.split(",")
                val split1 = split[start - 1].split(":")
                Log.d("设置闹钟", split1[0] + split1[1])
                tv_alarmtime.setText("${split1[0]}:${split1[1]}")
            }else{
                val replace = default.replace("\n", "")
                val split = replace.split(",")
                val split1 = split[start - 1].split(":")
                Log.d("设置闹钟", split1[0] + split1[1])
                tv_alarmtime.setText("${split1[0]}:${split1[1]}")
            }
        }


        val pickview= MyPickerView(this)
        val pickview_weeks= MyPickerView(this)
        var listItem1=ArrayList<String>()
        var listItem2=ArrayList<String>()
        var listItem3=ArrayList<String>()
        var listItem4=ArrayList<String>()
        var listItem5=ArrayList<String>()
        listItem1.add("周一")
        listItem1.add("周二")
        listItem1.add("周三")
        listItem1.add("周四")
        listItem1.add("周五")
        listItem1.add("周六")
        listItem1.add("周日")
        val index = SPUtils.getInstance().getInt("lessoncounts", 8)
        for (i in 1..index){
            listItem2.add("第${i}节")
        }
        for (i in 1..index){
            listItem3.add("第${i}节")
        }
        pickview.setPicker(listItem1, listItem2, listItem3, false)
        pickview.setSelectOptions(day-1,start-1,step-1)
        ll_weekdays.setOnClickListener {
            pickview.show()
        }
        pickview.setOnoptionsSelectListener { options1, option2, options3 ->
            if (options3<option2){
                ToastUtils.showShort("不符合规则,请重新选择")
            }else{
                start=option2+1
                step=options3+1
                day=options1+1
                Log.d("zlytest", "${options1},${option2},${options3}")
                tv_weekdays.text = listItem1.get(options1)+listItem2.get(option2)+listItem2.get(
                    options3
                )
            }
            if (SPUtils.getInstance().getString("lessontime")!=null&&!SPUtils.getInstance().getString(
                    "lessontime"
                ).isEmpty()){
                val replace = SPUtils.getInstance().getString("lessontime").replace("\n", "")
                val split = replace.split(",")
                val split1 = split[start - 1].split(":")
                Log.d("设置闹钟", split1[0] + split1[1])
                tv_alarmtime.setText("${split1[0]}:${split1[1]}")
//                setSystemAlarmClock(this,"在${et_lesson_location.text.toString()}上${et_lesson_teacher.text.toString()}的${et_lesson_name.text.toString()}",split1[0].toInt(),split1[1].toInt())
            }else{
                val replace = default.replace("\n", "")
                val split = replace.split(",")
                val split1 = split[start - 1].split(":")
                Log.d("设置闹钟", split1[0] + split1[1])
                tv_alarmtime.setText("${split1[0]}:${split1[1]}")
//                setSystemAlarmClock(this,"在${et_lesson_location.text.toString()}上${et_lesson_teacher.text.toString()}的${et_lesson_name.text.toString()}",split1[0].toInt(),split1[1].toInt())
            }
        }
        for (i in 1..25){
            listItem4.add("第" + i.toString() + "周")
            listItem5.add("第" + i.toString() + "周")
        }
        pickview_weeks.setPicker(listItem4, listItem5, false)
        ll_weeks.setOnClickListener {
            pickview_weeks.show()
        }
        pickview_weeks.setOnoptionsSelectListener { options1, option2, options3 ->
            if (options1>option2){
                ToastUtils.showShort("不符合规则,请重新选择")
            }else{
                tv_weeks.text = "${listItem4.get(options1)}到${listItem5.get(option2)}"
                Log.d("zlytest", "${options1 + 1},${option2 + 1}")
                weeklist="${options1+1},${option2+1}"
            }
        }
        ll_alarm.setOnClickListener {
            ActivityUtils.startActivity(Intent(AlarmClock.ACTION_SHOW_ALARMS))
        }
    }

    override fun initData(savedInstanceState: Bundle?) {

    }

    fun setSystemAlarmClock(context: Context, message: String?, days: Int, hour: Int, minute: Int): Boolean {
        if (Build.VERSION.SDK_INT < 9) {
            return false
        }
        val testDays: ArrayList<Int> = ArrayList()
        when(days){
            1->testDays.add(Calendar.MONDAY)
            2->testDays.add(Calendar.TUESDAY)
            3->testDays.add(Calendar.WEDNESDAY)
            4->testDays.add(Calendar.THURSDAY)
            5->testDays.add(Calendar.FRIDAY)
            6->testDays.add(Calendar.SATURDAY)
            7->testDays.add(Calendar.SUNDAY)
        }
        val intent = Intent(AlarmClock.ACTION_SET_ALARM)
        intent.putExtra(AlarmClock.EXTRA_MESSAGE, message)
        intent.putExtra(AlarmClock.EXTRA_DAYS, testDays)
        intent.putExtra(AlarmClock.EXTRA_HOUR, hour)
        intent.putExtra(AlarmClock.EXTRA_MINUTES, minute)
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        if (Build.VERSION.SDK_INT >= 11) {
            intent.putExtra(AlarmClock.EXTRA_SKIP_UI, true)
        }
        if (Build.VERSION.SDK_INT >= 19) {
            intent.putExtra(AlarmClock.EXTRA_VIBRATE, true)
        }
        return try {
            context.startActivity(intent)
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

}